//
//  VideoUtil.swift
//  Tinsecret_TW
//
//  Created by wanghui on 2019/1/14.
//  Copyright © 2019年 tst. All rights reserved.
//

import UIKit
import AVFoundation

class VideoUtil: NSObject {
    static let instance = VideoUtil()
    
    override private init() {
    }
    
    //获取视频第一帧
    func getThumbnailImg(url:URL) -> UIImage? {
        //设置视频第一帧图片
        var asset: AVURLAsset = AVURLAsset.init(url: url, options: nil)
        let assetGen: AVAssetImageGenerator = AVAssetImageGenerator.init(asset: asset)
        assetGen.appliesPreferredTrackTransform = true
        let time: CMTime = CMTimeMakeWithSeconds(0.0, preferredTimescale: 600)
        let error: NSError
        var actualTime: CMTime =  CMTimeMake(value: 0, timescale: 0)
        do {
            let image: CGImage = try assetGen.copyCGImage(at: time, actualTime: &actualTime)
            return UIImage.init(cgImage: image)
        } catch {
            return nil
        }
    }

        
    //压缩视频
    //fromurl: 视频原来的路径
    //outputurl: 将视频压缩后存放到该路径
    func compressVideo(fromurl:URL, outputurl:URL, finish: @escaping (_ status:AVAssetExportSession.Status) -> Void) {
        
        let asset: AVURLAsset = AVURLAsset.init(url: fromurl, options: nil)
        let exportSession: AVAssetExportSession = AVAssetExportSession.init(asset: asset, presetName: AVAssetExportPresetMediumQuality)!
        exportSession.shouldOptimizeForNetworkUse = true
        exportSession.outputURL = outputurl
            exportSession.outputFileType = AVFileType.mp4
        exportSession.exportAsynchronously(completionHandler: {
            let exportStatus = exportSession.status
            print("exportStatus == \(exportStatus)")
            finish(exportStatus)
        })
    }
    
    //计算视频文件大小 (返回的是字节)   返回值除以 1024 再除以1024可以获得 M
    func fileSizeAtPath(filePath: String) -> Double {
        let manager = FileManager.default
        if manager.fileExists(atPath: filePath) {
            do {
                let attr = try manager.attributesOfItem(atPath: filePath)
                let size = attr[FileAttributeKey.size] as! Double
                return size
            } catch  {
                print("error :\(error)")
                return 0
            }
        }
        return 0
    }
    
    //计算视频的尺寸(宽高)
    func videoSizeAtPath(filePath: String) -> CGSize {
        let asset: AVURLAsset = AVURLAsset.init(url: URL.init(fileURLWithPath: filePath))
        let arr: NSArray = asset.tracks as NSArray
        var videoSize: CGSize = CGSize.zero
        for element in arr {
            let track: AVAssetTrack = element as! AVAssetTrack
            if (track.mediaType == .video) {
                videoSize = track.naturalSize
            }
        }
        return videoSize
    }
    
    //计算视频的时长
    func videoDuration(filePath: String) -> Int {
        let asset: AVURLAsset = AVURLAsset.init(url: URL.init(fileURLWithPath: filePath))
        let totalSeconds = Int(CMTimeGetSeconds(asset.duration))
        return totalSeconds
    }
    
    
    //起文件名 注意后缀是  .mp4
    func createVideoName(videoUrl: String) -> (String){
        let arr: NSArray = videoUrl.components(separatedBy: "/") as NSArray
        let tempStr: String = arr.lastObject as! String
        let finalStr = tempStr.replacingOccurrences(of: "-", with: "")
        let emArr: NSArray = finalStr.components(separatedBy: ".") as NSArray
        let lastFinalStr: String = emArr.firstObject as! String
        print("lastFinalStr = \(lastFinalStr)")
        // uid + time + random
        return String(AppStatusManager.instance.userLoginStatus.1!) + lastFinalStr + String(Int(arc4random()%1000)+1) + ".mp4"
    }
        
}

